<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 * ============================================================================
 * $Author: IT宇宙人 2015-08-10 $
 */
namespace Home\Controller;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use \PayPal\Api\Payer;
use \PayPal\Api\Item;
use \PayPal\Api\ItemList;
use \PayPal\Api\Details;
use \PayPal\Api\Amount;
use \PayPal\Api\Transaction;
use \PayPal\Api\RedirectUrls;
use PayPal\Api\ShippingAddress;
use \PayPal\Exception\PayPalConnectionException;

class CartController extends BaseController {

    public $cartLogic; // 购物车逻辑操作类
    public $user_id = 0;
    public $user = array();
    /**
     * 初始化函数
     */
    public function _initialize(){
        parent::_initialize();
        $this->cartLogic = new \Home\Logic\CartLogic();

        if(session('?user'))
        {
            $user = session('user');
            $user = M('users')->where("user_id = {$user['user_id']}")->find();
            session('user',$user);  //覆盖session 中的 user
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user',$user); //存储用户信息
            // 给用户计算会员价 登录前后不一样
            if($user){
                $user[discount] = (empty($user[discount])) ? 1 : $user[discount];
                M('Cart')->execute("update `__PREFIX__cart` set member_goods_price = goods_price * {$user[discount]} where (user_id ={$user[user_id]} or session_id = '{$this->session_id}') and prom_type = 0");
            }
        }



    }

    public function cart(){
        $this->display();
    }

    public function index(){
        $this->display('cart');
    }

    /**
     * ajax 将商品加入购物车
     */
    function ajaxAddCart()
    {
        $goods_id = I("goods_id"); // 商品id
        $goods_num = I("goods_num");// 商品数量
        $goods_spec = I("goods_spec"); // 商品规格
        $result = $this->cartLogic->addCart($goods_id, $goods_num, $goods_spec,$this->session_id,$this->user_id); // 将商品加入购物车
        exit(json_encode($result));
    }


    public function paypal_init(){
        require "vendor/autoload.php"; //载入sdk的自动加载文件
        define('SITE_URL', 'http://www.wawa.com'); //网站url自行定义  如果是本地是 localhost/后面的看你自己的代码位置pay.php的位置 写到文件夹的位置就可以
        //创建支付对象实例
      $cliend_id='AbvQHzCTPTnEerH0rnJ72jOtN0eGk9zIijnjOOIMOi-5hrSQUC0IogYYhrC0N7ArxM38urJSBasprG3P';
      $secret='EMXJotAR4EdxnQEWz8z6CSWXcsLhOgbNVgFzBZPGA151vktOf6LlYtjxFYYeKgQbgphMvt9_yVqBt2lt';
//        $cliend_id='AaVZC0rg_3h1N5tSm1NlwVaSr7Jhak30SHYEkTqCwoFALYBqHk_OpJJc1nxnq_6jITnP5PEfIPAKd4dM';
//        $secret='EMMrl0W_WMoWTJxVYydg3u3CJiwW0k7WCHy-HETGGe2109QLWVSqduiInrobwibCgqXHLfrJuAj8T92W';

        $paypal = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential($cliend_id,$secret)
        );
        return $paypal;
    }

    public function getCode(){
        $order_id=I('order_id');
        $order =M('order')->where(array('order_id'=>$order_id))->find();
        $g_address =M('user_address')->where(array('address_id'=>$order['g_address_id']))->find();
        $paypal=$this->paypal_init();


        $product = $order['order_id'];
        $price=$order['goods_price'];
        $shipping=$order['shipping_price'];
        $total =$price+$shipping;


        $exchange   =M('exchange_rate')->where(array('id'=>$order['currency']))->find();
        $money_code=$exchange['title'];//收款的币种代号

        $payer = new Payer();
        $payer->setPaymentMethod('paypal');



        $item = new Item();
        $item->setName($product)
            ->setCurrency($money_code)
            ->setQuantity(1)
            ->setPrice($price);

        $itemList = new ItemList();
        $itemList->setItems([$item]);

        //设置收货地址
//        $address = new ShippingAddress();
//        $address->setRecipientName($g_address['consignee'])
//            ->setLine1($g_address['address'])
//            ->setLine2('什么单元什么号')
//            ->setCity($g_address['city'])
//            ->setState('浙江省')
//            ->setPhone($g_address['mobile'])
//            ->setPostalCode($g_address['zipcode'])
//            ->setCountryCode('CN');
//        $itemList->setShippingAddress($address);

        $details = new Details();
        $details->setShipping($shipping)
            ->setSubtotal($price);

        $amount = new Amount();
        $amount->setCurrency($money_code)
            ->setTotal($total)
            ->setDetails($details);

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription("支付描述内容")
            ->setInvoiceNumber(uniqid());

        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl(SITE_URL . '/index.php?m=Home&c=cart&a=pay&order_sn='.$order[order_sn].'&success=true')
            ->setCancelUrl(SITE_URL . '/index.php?m=Home&c=Cart&a=cart4&order_id='.$order[order_id].'&success=false');
        $payment = new Payment();
        $payment->setIntent('sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions([$transaction]);

        try {
            $payment->create($paypal);
        } catch (PayPalConnectionException $e) {
            echo $e->getData();
            die();
        }
        $approvalUrl = $payment->getApprovalLink();

                    exit(json_encode($approvalUrl));
//        print_r($approvalUrl);exit;
    }









    public function pay(){
        $paypal=$this->paypal_init();
        if(!isset($_GET['success'], $_GET['paymentId'], $_GET['PayerID'])){
            die();
        }
        if((bool)$_GET['success']=== 'false'){
            $this->error('支付失败，请重试！');
//            echo 'Transaction cancelled!';
//            die();
        }

        $paymentID = $_GET['paymentId'];
        $payerId = $_GET['PayerID'];

        $payment = Payment::get($paymentID, $paypal);

        $execute = new PaymentExecution();
        $execute->setPayerId($payerId);

        try{
            $result = $payment->execute($execute, $paypal);
        }catch(Exception $e){
            die($e);
        }

        //改变订单状态
        $order_sn=I('order_sn');
        $order=M('order')->where(array('order_sn'=>$order_sn))->find();
        update_pay_status($order_sn);
        $this->success('支付成功',U('Home/User/order_detail',array('id'=>$order['order_id'])));
//        echo '支付成功！感谢支持!';
//
//
//
//        dump($result);exit;
//
//        exit;
    }

    public function ajaxAddCartNew(){
        $user_id=$this->user_id;
        $session_id=$this->session_id;
        $goods_id =I('goods_id');
        $attach =I('attach');
        $submit =I('get.submit');
        I('unm')?$goods_num =I('unm'):$goods_num=1;
        $goods=M('goods')->where("goods_id=$goods_id")->find();
        if(!$goods)
            exit(json_encode(array('status'=>-1,'msg'=>'Product does not exist')));

        //计算商品连附带品价格
//        $money = get_goods_price($goods_id,$attach,$goods_num);
        $price_arr = get_goods_price($goods_id,$attach,$goods_num);
        $price=$price_arr['goods_price_n'];
        $old_price=$price_arr['old_goods_price_n'];
        $old_hl_price=$price_arr['old_hl_goods_price_n'];

        $money_str=get_money_str();

        if($submit>0){
            $attach_j = json_encode($attach);
            $where = " goods_id = $goods_id and attach = '$attach_j' "; // 查询购物车是否已经存在这商品
            if($this->user_id > 0)
                $where .= " and (session_id = '$session_id' or user_id = $user_id) ";
            else
                $where .= " and  session_id = '$session_id' ";

            $catr_goods = M('Cart')->where($where)->find(); // 查找购物车是否已经存在该商品

            if($catr_goods['id']){
                $result = M('Cart')->where("id =".$catr_goods[id])->save(  array("goods_num"=> ($catr_goods['goods_num'] + $goods_num)) ); // 数量相加
                $cart_count = cart_goods_num($user_id,$session_id); // 查找购物车数量
                setcookie('cn',$cart_count,null,'/');
//                return array('status'=>1,'msg'=>'成功加入购物车','result'=>$cart_count);
                exit(json_encode(array('status'=>1,'msg'=>'Successfully added to the shopping cart','result'=>$cart_count)));
            }else{



                $data = array(
                    'user_id'         => $this->user_id,   // 用户id
                    'session_id'      => $this->session_id,   // sessionid
                    'goods_id'        => $goods_id,   // 商品id
                    'goods_num'       => $goods_num, // 购买数量
                    'add_time'        => time(), // 加入购物车时间
                    'attach'        => $attach_j, // 附属商品数组
                    'goods_sn'        => $goods['goods_sn'],   // 商品货号
                    'goods_name'      => $goods['goods_name'],   // 商品名称
                    'goods_price'     => $old_price,  // 购买价
                    'member_goods_price'     => $old_price,  // 购买价

                );

                $insert_id = M('Cart')->add($data);
                $cart_count = cart_goods_num($user_id,$session_id); // 查找购物车数量
                setcookie('cn',$cart_count,null,'/');
                exit(json_encode(array('status'=>1,'msg'=>'Successfully added to the shopping cart','result'=>$cart_count)));
            }

        }

         $re_arr['price']= sprintf('%.2f',$price);;
        $re_arr['old_hl_price']= sprintf('%.2f',$old_hl_price);;
        $re_arr['money_str']=$money_str;
        exit(json_encode($re_arr));

    }




    /**
     * ajax 删除购物车的商品
     */
    public function ajaxDelCart()
    {
        $ids = I("ids"); // 商品 ids
        $result = M("Cart")->where(" id in ($ids)")->delete(); // 删除id为5的用户数据
        $return_arr = array('status'=>1,'msg'=>'Successfully deleted','result'=>''); // 返回结果状态
        exit(json_encode($return_arr));
    }


    /*
     * ajax 请求获取购物车列表
     */
    public function ajaxCartList()
    {


        $post_goods_num = I("goods_num"); // goods_num 购物车商品数量
        $post_cart_select = I("cart_select"); // 购物车选中状态
        $where = " session_id = '$this->session_id' "; // 默认按照 session_id 查询
        $this->user_id && $where = " user_id = ".$this->user_id; // 如果这个用户已经等了则按照用户id查询
        $cartList = M('Cart')->where($where)->getField("id,goods_id,goods_num,selected,prom_type,prom_id,member_goods_price,goods_price");

        //所有促销活动
        $now = time();
        $where_order = "end_time>$now and start_time<$now and is_close='1'";
        $prom_order = M('prom_order')->where($where_order)->order("id asc")->select();//当前只判断

        //筛选活动
        $promid_str='';
        $narr=array();
        foreach($cartList AS $a=>$b){

            foreach($prom_order AS $x=>$y){
                $goods_arr = explode(',',$y['goods_id']);

                if(in_array($b['goods_id'],$goods_arr)&&!in_array($y['id'],$narr)){
                    $narr[]=$y['id'];
                    $promid_str?$promid_str.=','.$y['id']:$promid_str.=$y['id'];
                }
            }
        }
        if($promid_str)
        {
            $where_order_n=$where_order.' and ( id in('.$promid_str.') or type in(0,1,2,3))';

        }else{
            $where_order_n=$where_order.' and type in(0,1,2,3)';
        }

        $prom_order = M('prom_order')->where($where_order_n)->order("id asc")->select();//当前只判断
        $this->assign('promname', $prom_order);


        if(I('hd_id'))
        {
            $hdid = I('hd_id'); // 促销类型
        }
        else
        {
            if($prom_order)
            {
                $hdid = $prom_order[0][id]; // 促销类型
            }
        }

        $this->assign('hd_id',$hdid); // 促销类型



        if($post_goods_num)
        {
            // 修改购物车数量 和勾选状态
            foreach($post_goods_num as $key => $val)
            {
                $data['goods_num'] = $val < 1 ? 1 : $val;

//                if($cartList[$key]['prom_type'] == 1) //限时抢购 不能超过购买数量
//                {
//                    $flash_sale = M('flash_sale')->where("id = {$cartList[$key]['prom_id']}")->find();
//                    $data['goods_num'] = $data['goods_num'] > $flash_sale['buy_limit'] ? $flash_sale['buy_limit'] : $data['goods_num'];
//                }
//                $data['selected'] = $post_cart_select[$key] ? 1 : 0 ;
                $data['selected'] = 1 ;
                if(($cartList[$key]['goods_num'] != $data['goods_num']) || ($cartList[$key]['selected'] != $data['selected'])) //判断数量以及选中状态变更的时候更保存数量及选中状态
                    M('Cart')->where("id = $key")->save($data);
            }
            $this->assign('select_all', $_POST['select_all']); // 全选框
        }

        $result = $this->cartLogic->cartList($this->user, $this->session_id,1,1,$hdid); // 选中的商品
        if(empty($result['total_price']))
            $result['total_price'] = Array( 'total_fee' =>0, 'cut_fee' =>0, 'num' => 0);

        $this->assign('cartList', $result['cartList']); // 购物车的商品
        $this->assign('total_price', $result['total_price']); // 总计
        $this->display('ajax_cart_list');
    }


    public function get_goods_sort($promcondition,$goods_num)

    {
        $count=count($promcondition)-1;
        if($goods_num<$promcondition[0]){
            $sort='l';
        }elseif($goods_num>=$promcondition[$count]){
            $sort='d';
        }else{
            foreach($promcondition as $key2 => $val2){
                if($goods_num<$val2){
                    $sort=$key2;
                    return $sort;
                }
            }
        }

        return $sort;
    }

    /**
     * 购物车第二步确定页面
     */
    public function cart2()
    {




        $hd_id=I('hd_id');
        $this->assign('hd_id', $hd_id); // 促销活动id


         if($this->user_id == 0)
             $this->error('Please login user.',U('Home/User/login'));

        /*判断当前用户ID购物车是否有商品，否则将不能继续结算
        */


        if(!$this->user_id)
        {
            //array('sessionid_id'=>$this->session_id,'is_pickup'=>0)
            $address_list = M('user_address')->where(array('sessionid_id'=>$this->session_id,'is_pickup'=>0))->select();
        }
        else
        {
            $address_list = M('user_address')->where('user_id = '.$this->user_id.' AND is_pickup = 0')->select();
        }
        $this->assign('address_list', $address_list); // 优惠券列表

        if(!$this->user_id)
        {
            $arr['session_id']=$this->session_id;
            $arr['selected']=1;
            $c = M('Cart')->where($arr)->count();
            if(empty($c))
                $this->error ('Your shopping cart is not selected','Cart/cart');
        } else {
            if($this->cartLogic->cart_count($this->user_id,1) == 0 )
                $this->error ('Your shopping cart is not selected','Cart/cart');
        }
        $result = $this->cartLogic->cartList($this->user, $this->session_id,1,1,$hd_id); // 获取购物车商品


        $shippingList = M('Plugin')->where("`type` = 'shipping' and status = 1")->order('code asc')->select();// 物流公司

        /*登录情况读取优惠券信息*/
        if($this->user_id)
        {
            $Model = new \Think\Model(); // 找出这个用户的优惠券 没过期的
            $sql = "select c1.name,c1.id,c1.cateid,c1.money,c1.expression,c1.condition, c2.* from __PREFIX__coupon as c1 inner join __PREFIX__coupon_list as c2  on c2.cid = c1.id and c1.type in(0,1,2,3,4,5) and order_id = 0  where c2.uid = {$this->user_id}  and ".time()." < c1.use_end_time ";
            $couponList = $Model->query($sql);

            //优惠券筛选
            foreach($couponList AS $ke=>$va){
                $coupon=M('coupon')->where("id=".$va['cid'])->find();
                if($coupon['cateid']==1&&$result['total_price']['total_fee']<$coupon['condition'] ){
                    unset($couponList[$ke]);
                }elseif($coupon['cateid']==3&&$result['total_price']['total_fee']<$coupon['money']){
                    unset($couponList[$ke]);
                }
            }
            // 优惠券筛选 订单金额达到 condition 优惠券指定标准的
            $this->assign('couponList', $couponList); // 优惠券列表
        }


	
//        $this->assign('couponList', $couponList); // 优惠券列表
        $this->assign('shippingList', $shippingList); // 物流公司
        $this->assign('cartList', $result['cartList']); // 购物车的商品
        $this->assign('total_price', $result['total_price']); // 总计
        $this->assign('userstate', $this->user_id); // 用户状态
        $this->display();
    }

    /**
     * ajax 获取用户收货地址 用于购物车确认订单页面
     */
    public function ajaxAddress(){
        $model = M('UserAddress');
        if(!$this->user_id)
        {
            //array('sessionid_id'=>$this->session_id,'is_pickup'=>0)
            $address_list = $model->where(array('sessionid_id'=>$this->session_id,'is_pickup'=>0))->select();
        }
        else
        {
            $address_list = $model->where('user_id = '.$this->user_id.' AND is_pickup = 0')->select();
        }



//        if($address_list){
//            $area_id = array();
//            foreach ($address_list as $val){
//                $area_id[] = $val['province'];
//                $area_id[] = $val['city'];
//                $area_id[] = $val['district'];
//                $area_id[] = $val['twon'];
//            }
//
//            $area_id = array_filter($area_id);
//            $area_id = implode(',', $area_id);
//            $regionList = M('region')->where("id in ($area_id)")->getField('id,name');
//            $this->assign('regionList', $regionList);
//        }
        $address_where['is_default'] = 1;

        if(!$this->user_id)
        {

            $c = $model->where(array('sessionid_id'=>$this->session_id,'is_default'=>1,'is_pickup'=>0))->count(); // 看看有没默认收货地址
        }
        else
        {
            $c = $model->where('user_id = '.$this->user_id.' AND is_default=1 AND is_pickup = 0')->count(); // 看看有没默认收货地址
        }
        if((count($address_list) > 0) && ($c == 0)) // 如果没有设置默认收货地址, 则第一条设置为默认收货地址
            $address_list[0]['is_default'] = 1;

        $this->assign('address_list', $address_list);
        $this->display('ajax_address');
    }

    public function test(){
        $user_id = 18991;
        echo crc32($user_id);
    }

    /**
     * @author dyr
     * @time 2016.08.22
     * 获取自提点信息
     */
    public function ajaxPickup()
    {
        $address_list = D('UserAddress')->getUserPickup($this->user_id);
        $province_id = I('province_id');
        $city_id = I('city_id');
        $district_id = I('district_id');
        if (empty($province_id) || empty($city_id) || empty($district_id)) {
            exit("<script>alert('Parameter error');</script>");
        }
        $pickup_list = D('Pickup')->getPickupItemByPCD($province_id, $city_id, $district_id);
        $this->assign('pickup_list', $pickup_list);
        $this->assign('address_list', $address_list);
        $this->display('ajax_pickup');
    }

    /**
     * @author dyr
     * @time 2016.08.22
     * 更换自提点
     */
    public function replace_pickup()
    {
        $province_id = I('get.province_id');
        $city_id = I('get.city_id');
        $district_id = I('get.district_id');
        $region_model = M('region');
        $call_back = I('get.call_back');
        if (IS_POST) {
            echo "<script>parent.{$call_back}('success');</script>";
            exit(); // 成功
        }
        $address = array('province' => $province_id, 'city' => $city_id, 'district' => $district_id);
        $p = $region_model->where(array('parent_id' => 0, 'level' => 1))->select();
        $c = $region_model->where(array('parent_id' => $province_id, 'level' => 2))->select();
        $d = $region_model->where(array('parent_id' => $city_id, 'level' => 3))->select();
        $this->assign('province', $p);
        $this->assign('city', $c);
        $this->assign('district', $d);
        $this->assign('address', $address);
        $this->assign('call_back', $call_back);
        $this->display();
    }

    /**
     * @author dyr
     * @time 2016.08.22
     * 更换自提点
     */
    public function ajax_PickupPoint()
    {
        $province_id = I('province_id');
        $city_id = I('city_id');
        $district_id = I('district_id');
        $pick_up_model = D('Pickup');
        $pick_up_list = $pick_up_model->getPickupListByPCD($province_id,$city_id,$district_id);
        exit(json_encode($pick_up_list));
    }


    /**
     * ajax 获取订单商品价格 或者提交 订单
     */
    public function cart3(){
        $nosubmit =  I("nosubmit");
        $hd_id = I("hd_id"); //  促销活动id
        $shipping_code =  I("shipping_code"); //  物流编号
        $invoice_title = I('invoice_title'); // 发票
        $coupon_id =  I("coupon_id"); //  优惠券id
        $couponCode =  I("couponCode"); //  优惠券代码
        $user_money =  I("user_money",0); //  使用余额
        if(!$this->user_id)
        {
            $arr['session_id']=$this->session_id;
            $arr['selected']=1;
            $c = M('Cart')->where($arr)->count();

            if(empty($c))
            {
                exit(json_encode(array('status'=>-2,'msg'=>'Your shopping cart is not selected','result'=>null)));
            }
        }
        else
        {
            if($this->cartLogic->cart_count($this->user_id,1) == 0 )
            {
                exit(json_encode(array('status'=>-2,'msg'=>'Your shopping cart is not selected','result'=>null)));
            }
        }
        if(!$nosubmit)//判断假如不是提交订单不进行查询是否收货人
        {
            //勾选了创建用户信息的
            $data=I();
            $user_id=$_SESSION['user']['user_id'];
            $session_id=session_id();
            if($user_id){//登录状态
                if($data['g_address_id']){//选择了已有地址
                    $g_address_id=$data['g_address_id'];
                }else{
                    $data['g_address']['user_id']=$user_id;
                    $g_address_id=M('user_address')->add($data['g_address']);
                }
                if($data['address_2_cp']){//发票地址与收件地址一致的
                    $f_address_id=$g_address_id;
                }else{//发票地址与收件地址不一致的
                    if($data['f_address_id']){
                        $f_address_id=$data['f_address_id'];
                    }else{
                        $data['f_address']['user_id']=$user_id;
                        $f_address_id=M('user_address')->add($data['f_address']);
                    }

                }
            }
//            else{//非登录状态
//                if($data['create_account']){//需要创建账户的
//                    //创建一个账户
//                    $add_user_data = $logic->reg($data['g_address']['email'],$data['password'],$data['c_password']);
//                    $n_user_id=$add_user_data['result']['user_id'];
//                    //增加收件地址
//                    $data['g_address']['user_id']=$n_user_id;
//                    $g_address_id=M('user_address')->add($data['g_address']);
//                }else{//不创建账户的
//                    $data['g_address']['sessionid_id']=$session_id;
//                    $g_address_id=M('user_address')->add($data['g_address']);
//                }
//                if($data['address_2_cp']){//发票地址与收件地址一致的
//                    $f_address_id=$g_address_id;
//                }else{//发票地址与收件地址不一致的
//                    if($n_user_id){//如果已经创建了账户的
//                        $data['f_address']['user_id']=$n_user_id;
//                        $f_address_id=M('user_address')->add($data['g_address']);
//                    }else{//没有创建账户的
//                        $data['f_address']['sessionid_id']=$session_id;
//                        $f_address_id=M('user_address')->add($data['f_address']);
//                    }
//                }
//            }
        }
        $result_price = $this->cartLogic->cartList($this->user, $this->session_id,1,2,$hd_id); // 获取购物车商品
        //查看满多少包邮
        $freight_free=M('config')->where("name='freight_free'")->find();
        if($result_price['result']['total_price']['total_fee']>=$freight_free['value']){
            $shipping_price=0; //商品总金额不小于最底包邮价 运费==0
        }else{
            //查询默认运费
            $default_postage=M('config')->where("name='default_postage'")->find();
            $shipping_price=get_hl_price_1($default_postage['value']);//商品总金额小于最底包邮价 运费==默认邮费
        }


			
        $result=order_price($this->user_id,$result_price['result']['total_price'],$shipping_price,$coupon_id);
        if($result_price['status'] < 0)
            exit(json_encode($result));

        // 订单满额优惠活动



        $car_price = array(
            'postFee'      => $result['result']['shipping_price'], // 物流费
            'couponFee'    => $result['result']['coupon_price'], // 优惠券
            'payables'     => $result['result']['order_amount'], // 应付金额
            'goodsFee'     => $result['result']['goods_price'],// 商品价格
            'order_prom_id' => $hd_id, // 订单优惠活动id
            'order_prom_amount' => $result['result']['order_prom_amount'], // 订单优惠活动优惠了多少钱
            'money_str' => $result_price['result']['total_price']['money_str'], //  货币符号str
        );
        // 提交订单

        if($_REQUEST['act'] == 'submit_order')
        {
            if(empty($coupon_id) && !empty($couponCode))
                $coupon_id = M('CouponList')->where("`code`='$couponCode'")->getField('id');
            $result = $this->cartLogic->addOrder($this->user_id,$g_address_id,$f_address_id,$shipping_code,$invoice_title,$coupon_id,$car_price,$hd_id); // 添加订单
            if($result['status']==1){
                $order_id =$result['result'];
                $order =M('order')->where(array('order_id'=>$order_id))->find();
                $user=M('users')->where(array('user_id'=>$user_id))->find();
                $to_email =$user['email'];
                $title='Secret-Doll.com: New Order # '.$order['order_sn'];
                $content=  $this->get_order_email_content($order_id);
                 send_email($to_email,$title,$content);    //发送邮件通知
            }

            exit(json_encode($result));
        }
        $return_arr = array('status'=>1,'msg'=>'Calculated successfully','result'=>$car_price); // 返回结果状态
        exit(json_encode($return_arr));
    }



    /**   获取邮件模板
     * @param $order_id  订单id
     * @return mixed
     */
    function get_order_email_content($order_id){
        $order=M('order')->where(array('order_id'=>$order_id))->find();
        $goods_list=M('order_goods')->where(array('order_id'=>$order_id))->select();
        $g_address=M('user_address')->where(array('address_id'=>$order['g_address_id']))->find();
        $f_address=M('user_address')->where(array('address_id'=>$order['f_address_id']))->find();
        $money_str=get_money_str();
        $this->assign('money_str', $money_str);
        $this->assign('goods_list', $goods_list);
        $this->assign('g_address', $g_address);
        $this->assign('f_address', $f_address);
        $this->assign('order', $order);
        $content = $this->fetch('order_email_content');
        return $content;
    }



    /**
     * ajax 获取订单商品价格 或者提交 订单
     * 已经用心方法 这个方法 cart9  准备作废
     */

    /*
     * 订单支付页面
     */
    public function cart4(){


        $order_id = I('order_id');
        $order = M('Order')->where("order_id = $order_id")->find();
        // 如果已经支付过的订单直接到订单详情页面. 不再进入支付页面
        if($order['pay_status'] == 1){
            $order_detail_url = U("Home/User/order_detail",array('id'=>$order_id));
            header("Location: $order_detail_url");
        }
        if($order['user_id'] != 1){

            $arr['order_id']=$order['order_id'];
            $c = M('sms_log')->where($arr)->count();
            if(!$c)
            {
                //$send = sendSMS($order['mobile'],$order['order_sn'],$order['order_id']);
                $OrderLogic = new \Home\Logic\OrderLogic();
                $send = $OrderLogic->sms_log($order['mobile'],$order['order_sn'],$order['order_id']);
            }
        }
        $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and  scene in(0,2)")->select();
        $paymentList = convert_arr_key($paymentList, 'code');
        foreach($paymentList as $key => $val)
        {
            $val['config_value'] = unserialize($val['config_value']);
            if($val['config_value']['is_bank'] == 2)
            {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
        }

        $bank_img = include 'Application/Home/Conf/bank.php'; // 银行对应图片             
        $this->assign('paymentList',$paymentList);
        $this->assign('bank_img',$bank_img);
        $this->assign('mobilesn',$c);
        $this->assign('order',$order);
        $this->assign('bankCodeList',$bankCodeList);
        $this->assign('pay_date',date('Y-m-d', strtotime("+1 day")));
        $this->display();
    }


    public function order_detail(){
        $id = I('get.id');

        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = M('order')->where($map)->find();
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性


        if(!$order_info){
            $this->error('Did not get the order information');
            exit;
        }
        //获取订单商品

        $model = new \Home\Logic\UsersLogic();
        $data = $model->get_order_goods($order_info['order_id']);
        $order_info['goods_list'] = $data['result'];
        //$order_info['total_fee'] = $order_info['goods_price'] + $order_info['shipping_price'] - $order_info['integral_money'] -$order_info['coupon_price'] - $order_info['discount'];
        //获取订单进度条
        $sql = "SELECT action_id,log_time,status_desc,order_status FROM ((SELECT * FROM __PREFIX__order_action WHERE order_id = $id AND status_desc <>'' ORDER BY action_id) AS a) GROUP BY status_desc ORDER BY action_id";
        $items = M()->query($sql);
        $items_count = count($items);
        $region_list = get_region_list();

        $invoice_no = M('DeliveryDoc')->where("order_id = $id")->getField('invoice_no',true);
        $order_info[invoice_no] = implode(' , ', $invoice_no);
        //获取订单操作记录
        $order_action = M('order_action')->where(array('order_id'=>$id))->select();
        if($order_info['shipping_status'] == 1){
            $express = queryExpress($order_info['shipping_code'],$order_info['invoice_no']);
            $this->assign('express',$express);
        }
        $this->assign('order_status',C('ORDER_STATUS'));
        $this->assign('shipping_status',C('SHIPPING_STATUS'));
        $this->assign('pay_status',C('PAY_STATUS'));
        $this->assign('region_list',$region_list);
        $this->assign('return_order',$return_order);
        $this->assign('order_info',$order_info);
        $this->assign('order_action',$order_action);
        $this->assign('active','order_list');
        $this->display();
    }

    //ajax 请求购物车列表
    public function header_cart_list()
    {
        $cart_result = $this->cartLogic->cartList($this->user, $this->session_id,0,1);
        if(empty($cart_result['total_price']))
            $cart_result['total_price'] = Array( 'total_fee' =>0, 'cut_fee' =>0, 'num' => 0);

        $this->assign('cartList', $cart_result['cartList']); // 购物车的商品
        $this->assign('cart_total_price', $cart_result['total_price']); // 总计
        $template = I('template','header_cart_list');
        $this->display($template);
    }
}
